﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;

namespace ywwApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public List<Product> productlist = new List<Product>();

        public ActionResult Index()
        {
            //ViewData["products"] = GetJson("抽纸");
            return View();
        }
        //[HttpPost]
        //public ActionResult Index(string keyword, string address)
        //{
        //    //HttpCookie cookie = new HttpCookie("cookiekey");
        //    //cookie.Value = "name1";

        //    ViewData["products"] = GetJson(keyword);
        //    return View();
        //}

        public string CanBuy(string area, int skuid)
        {
            try
            {
                //{"success":true,"resultMessage":"","resultCode":"0000","result":[{"skuId":1127726,"areaId":"19_1607_4773_0","stockStateId":34,"stockStateDesc":"无货","remainNum":-1}],"code":"0","msg":null}

                string jsonp = string.Format("{{\"area\":\"{0}\",\"skuNums\":[{{\"num\":1,\"skuId\":{1}}}]}}", area, skuid);
                var pstr = HttpHelper.HttpPost("https://api.9yiwu.com/jdapi-service/storage/query?accessToken=&mChannal=NG_APP", jsonp);
                var json = JObject.Parse(pstr);
                if (json["resultCode"].ToString() == "0000")
                {
                    string m = json["result"][0]["stockStateDesc"].ToString();
                    if (m == "无货")
                    {
                        return "配送区域无货";
                    }
                    else
                    {
                        return "有货";
                    }
                }
                return "无货";
            }
            catch (Exception ex)
            {
                return "程序异常";
            }

        }

        public List<Product> GetJson(string name, string type)
        {
            string jsonp = "{\"brandIds\":[],\"catalogIds\":[],\"content\":\"" + name + "\",\"direction\":\"DESC\",\"page\":0,\"size\":10000,\"storeCodes\":[]}";


            var pstr = HttpHelper.HttpPost("https://m.9yiwu.com/search-service/es/product/query", jsonp);
            var json = JObject.Parse(pstr);

            //string url = string.Format("https://api.9yiwu.com/search-service/product/query?names={0}&pageNo=0&pageSize=50000&status=1&accessToken=&mChannal=NG_APP", name);
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //WebResponse response = request.GetResponse();
            //Stream resStream = response.GetResponseStream();
            //StreamReader sr = new StreamReader(resStream);
            //string strfile = sr.ReadToEnd();
            //var json = JObject.Parse(strfile);
            var result = json["products"];
            if (json["total"].ToString() != "0")
            {
                for (int i = 0; i < result.Count(); i++)
                {
                    //var title = result[i]["name"].ToString();
                    var arry = type.Split(',');
                    if (arry.Contains(result[i]["storeName"].ToString()) || arry.Contains("全部"))
                    {
                        var goods = new Product
                        {
                            Title = result[i]["name"].ToString().Length > 70 ? result[i]["name"].ToString().Substring(0, 70) : result[i]["name"].ToString(),
                            Price = double.Parse(result[i]["price"].ToString()),
                            Image = result[i]["picture"].ToString()
                        };
                        productlist.Add(goods);
                    }
                }
            }
            productlist = productlist.OrderByDescending(a => a.Price).ToList();
            return productlist;
        }

        public ActionResult GoodsList(string keyword, string type)
        {
            ViewData["products"] = GetJson(keyword, type);
            return PartialView("GoodsList");
        }
    }

    public class Product
    {
        public string Title { get; set; }
        public double Price { get; set; }
        public string Image { get; set; }
        public string TpProductId { get; set; }
    }
}
